package com.icss.clothes.service.imp;

import com.icss.clothes.entity.Orders;
import com.icss.clothes.entity.Remark;
import com.icss.clothes.mapper.OrderMapper;
import com.icss.clothes.mapper.RemarkMapper;
import com.icss.clothes.mapper.UserMapper;
import com.icss.clothes.service.IRemarkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

//关于评论模块的Service
@Service
public class RemarkService implements IRemarkService {
    @Autowired
     private RemarkMapper remarkMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Override
    @Transactional()
    //添加评论
    public String addRemark(Remark remark) {
       Remark sameRemark = remarkMapper.selectRemarkByUidAndCid(remark);
       if(sameRemark!=null){
           return "您已经评论过该商品了";
       }
       //判断用户是否购买过该商品
       Orders userOrder=orderMapper.selectByUidAndCid(remark.getUser_id(),remark.getC_id());
//       if(userOrder==null){
//           return "您未购买过该商品,不能参与评论！";
//       }
        remarkMapper.addRemark(remark);
       //添加完以后更新商品评分
        double oldScore= remarkMapper.selectScoreByCid(remark.getC_id());
        double newScore=remark.getRemark_score();
        double score=(oldScore+newScore)/2;
        remarkMapper.updateScoreByCid(remark.getC_id(),score);
        return "评论成功!感谢您的评论";
    }

    @Override
    //根据商品id查询评论
    public List<Remark> selectRemarkByCid(int cid) {
        List<Remark> remarkList = remarkMapper.selectRemarkByCid(cid);
        //遍历评论集合，获取评论的用户名
        for (Remark remark:remarkList) {
            remark.setUser_name(userMapper.selectUnameByUid(remark.getUser_id()));
        }
        return remarkList;
    }

}
